const sendMessage = (receiver, text) => {
  if (text || text != '') {
    let options = {
      receiver: receiver,
      details: {
        text: text
      }
    };
  
    Meteor.call('sendMessage', options);
  }
};

Template.messages_chatroom_input.onCreated(function () {
  this.friendId = Session.get('class.messages.chatroomFriendId');
  this.input = new ReactiveVar();
});

Template.messages_chatroom_input.events({
  'input #message-chatroom-input' (event, instance) {
    let text = $.trim(event.target.value);
    instance.input.set(text);
  },
  
  'keypress #message-chatroom-input' (event, instance) {
    if (event.keyCode === 13) {
      sendMessage(instance.friendId, instance.input.get());
      instance.input.set('');
      $('#message-chatroom-input').val('');
    }
  },

  'click #message-chatroom-submit' (event, instance) {
    sendMessage(instance.friendId, instance.input.get());
    instance.input.set('');
    $('#message-chatroom-input').val('');
  },
});